<template>
    <div>
        <el-input v-model="count" placeholder="请输入生成数组的个数"></el-input>
        <el-button @click="handleCreateNewArr"> 生成数组 </el-button>
    </div>
    <div>
        <span class="num" v-for="item in arr"  :key="item"> {{ item}} </span>
    </div>
    <div>
        <el-input-number :min="1" :max="arr.length" v-model="k"></el-input-number>
        <el-button @click="handleFindK"> 开始查找 </el-button>
        <div>
            第 {{ k }} 大的元素 为 {{knum}}
        </div>
    </div>
</template>

<script>


export default {
    name: "sort-k",
    data() {
        return {
            arr: [], //原始数组
            k: 2,    // 第几个元素
            count: 10,
            knum: '',

        }
    },
    methods: {
        handleCreateNewArr() {
            this.generateArr(this.count)
        },
        handleFindK() {
            this.knum = this.findK(this.k)
        },
        generateArr( count ) {
            let newArr = []
            for (let i=0; i< count; i++) {
                newArr.push(Math.ceil(Math.random() * 1000))
            }
            this.arr = newArr
            console.log("create new arr => ",this.arr)
        },
        findK(k) {  //查找第k大的元素
            if ( k < 1) {
                k = 1
            }
            if (k >this.arr.length) {
                k =this.arr.length
            }
            let sarr = []
            for (let i = 0; i < this.arr.length; i++) {
                let v = this.arr[i]
                if(sarr.length < k) {
                    if(sarr.length == 0) {
                          sarr.push(v)
                    } else {
                        for (let j = sarr.length-1; j >= 0; j--){
                            if (v > sarr[j]) {
                                if (j == 0 || v <= sarr[j-1]){
                                    sarr.splice(j,0, v)
                                    break
                                }
                            } else {
                                sarr.push(v)
                                break
                            }
                        }
                    }
                } else {
                    for (let j = sarr.length-1; j >= 0; j--){
                        if (v > sarr[j]) {
                            if (j == 0 || v <= sarr[j-1]){
                                sarr.splice(j,0, v)
                                sarr.pop()
                                break
                            }
                        }
                    }
                }
            }
            return sarr.pop()
        }
    }
}
</script>

<style  scoped>
    .num {
        background-color: burlywood;
        width: 50;
        margin-left: 20px;
    }
</style>
